<template>
  <v-dialog v-model="dialog" max-width="600px">
    <v-card>
      <v-card-title>
        <span class="text-h5">{{ tag ? '编辑标签' : '新建标签' }}</span>
      </v-card-title>

      <v-card-text>
        <v-form ref="form" v-model="valid">
          <v-container>
            <v-row>
              <v-col cols="12">
                <v-text-field
                  v-model="formData.name"
                  label="标签名"
                  :rules="[(v) => !!v || '标签名不能为空']"
                  required
                />
              </v-col>

              <v-col cols="12">
                <v-textarea v-model="formData.description" label="描述" rows="2" auto-grow />
              </v-col>
            </v-row>
          </v-container>
        </v-form>
      </v-card-text>

      <v-card-actions>
        <v-spacer />
        <v-btn text color="primary" @click="close">取消</v-btn>
        <v-btn text color="primary" :disabled="!valid" @click="save">保存</v-btn>
      </v-card-actions>
    </v-card>
  </v-dialog>
</template>

<script setup>
import { ref, watch } from 'vue'

const props = defineProps({
  modelValue: Boolean,
  tag: Object,
})

const emit = defineEmits(['update:modelValue', 'submit'])

const dialog = ref(false)
const valid = ref(false)
const form = ref(null)

const formData = ref({
  id: null,
  name: '',
  description: '',
})

watch(
  () => props.modelValue,
  (val) => {
    dialog.value = val
  },
)

watch(
  () => dialog.value,
  (val) => {
    emit('update:modelValue', val)
    if (!val) {
      resetForm()
    }
  },
)

watch(
  () => props.tag,
  (tag) => {
    if (tag) {
      formData.value = {
        id: tag.id || null,
        name: tag.name || '',
        description: tag.description || '',
      }
    }
  },
)

function resetForm() {
  formData.value = {
    id: null,
    name: '',
    description: '',
  }
  form.value?.resetValidation()
}

function close() {
  dialog.value = false
}

function save() {
  if (form.value?.validate()) {
    emit('submit', { ...formData.value })
    close()
  }
}
</script>
